using System.Collections.Generic;
using Magiq.Databases;
using Magiq.Delete;
using Magiq.Insert;
using Magiq.Query;
using Magiq.Sql.Support;
using Magiq.Update;

namespace Magiq.Sql
{
    public class MagiqToSql : MagiqToDatabases
    {
        private static IDatabaseAdapter GetDatabaseAdapterFrom<T>(IEnumerable<T> source)
        {
            var dataContext = source.DataContext();
            return dataContext == null ? null : new LinqToSqlDatabaseAdapter(dataContext);
        }

        protected override IDatabaseAdapter GetDatabaseAdapterFrom<T>(IUpdate<T> update)
        {
            return GetDatabaseAdapterFrom(update.Source);
        }

        protected override IDatabaseAdapter GetDatabaseAdapterFromDestination<TSource, TDestination, TNew>(IInsert<TSource, TDestination, TNew> insert)
        {
            return GetDatabaseAdapterFrom(insert.Destination);
        }

        protected override IDatabaseAdapter GetDatabaseAdapterFrom<T>(IDelete<T> delete)
        {
            return GetDatabaseAdapterFrom(delete.Source);
        }

        protected override IDatabaseAdapter GetDatabaseAdapterFrom<T>(IQuery<T> query)
        {
            return GetDatabaseAdapterFrom(query.Source);
        }

        protected override IDatabaseAdapter GetDatabaseAdapterFrom<TSource, TDestination, TNew>(IInsert<TSource, TDestination, TNew> insert)
        {
            if (!insert.Source.IsLinqToSqlStuff())
                return null;

            return GetDatabaseAdapterFrom(insert.Destination);
        }
    }
}